package org.gh.blackcloud.filter;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

public class ResourceReplaceWrapper extends HttpServletResponseWrapper {

	private PrintWriter cacheWriter;
	private CharArrayWriter bufferWriter;//用于保存截获的jsp内容
	
	public ResourceReplaceWrapper(HttpServletResponse response) {
		super(response);
		bufferWriter = new CharArrayWriter();
		// 这个是包装PrintWriter的，让所有结果通过这个PrintWriter写入到bufferedWriter中
		cacheWriter = new PrintWriter(bufferWriter);
	}

	/**
    *当一个继承了HttpServletResponseWrapper的包装器复写了getWriter()方法时
    *tomcat会把响应的内容塞入自定义的PrintWriter(cacheWriter)中
    */
	@Override
	public PrintWriter getWriter() throws IOException {
		return cacheWriter;
	}

	/**
	 * 获取页面
	 * @return
	 */
	public String result() {
		return bufferWriter.toString();
	}
}
